/*
 * File:    HttpDirectory.java
 * Created: 17-Jul-2007
 * Version: $Id$
 * 
 * COPYRIGHT (C) 2007, Bitgate Software, LLC.  All Rights Reserved.
 *
 * software@bitgatesoftware.com
 */

package com.bitgate.util.service.protocol.http;

import static com.bitgate.util.debug.Debug.*;

import java.io.File;
import java.util.Arrays;

import com.bitgate.util.encoder.SpaceEncoder;
import com.bitgate.util.mime.MimeTypes;

/**
 * This is a helper class that is used to generate the directory listing output for the user.  This will <i>eventually</i>
 * be replaced with a freemarker template that will do the same thing.
 * 
 * @author kenji
 * @since 0.6.0
 */
public class HttpDirectory
{
	/**
	 * Cuts off the display of a string after a certain length.
	 * 
	 * @param str The <code>String</code> to display.
	 * @param length The number of characters to cut off after, if the string exceeds this length.
	 * @return <code>String</code> containing the cut string after processing.
	 */
	public static String cutString(String str, int length) {
		if (str.length() > length) {
			return str.substring(0, length) + "...";
		}
		
		return str;
	}
	
	/**
	 * Creates a directory listing based on the user's initial request, and the root directory of the request.
	 * 
	 * @param initialRequest <code>String</code> containing the user's initial request.
	 * @param rootDirectory The <code>String</code> containing the root directory of the underlying request.
	 * @return <code>StringBuffer</code> containing the resulting directory listing.
	 */
	public static StringBuffer listDirectory(String initialRequest, String rootDirectory)
	{
		StringBuffer sBuffer = new StringBuffer();
		String copiedInitialRequest = initialRequest;
		
		if (!copiedInitialRequest.endsWith("/")) {
			copiedInitialRequest += "/";
		}
		
		String[] previousDirectories = copiedInitialRequest.split("\\/");
		String previousUrl = "/";
		boolean canShowPreviousUrl = false;
		
		if (isDebugEnabled()) {
			debug("Previous directory length = '" + previousDirectories.length + "'");
		}
		
		if (previousDirectories.length > 1) {
			for(int i = 0; i < previousDirectories.length - 1; i++) {
				if (previousDirectories[i].length() > 0) {
					previousUrl += SpaceEncoder.spaceEncode(previousDirectories[i]) + "/";
				}
			}
			
			copiedInitialRequest = "";
			
			for(String request : previousDirectories) {
				copiedInitialRequest += SpaceEncoder.spaceEncode(request) + "/";
			}
			
			canShowPreviousUrl = true;
		}
		
		sBuffer.append("<h1>");
		sBuffer.append(initialRequest);
		sBuffer.append("</h1>\n\n");
		
		if (canShowPreviousUrl) {
			sBuffer.append("[ <a href=\"");
			sBuffer.append(previousUrl);
			
			sBuffer.append("\">Previous Directory</a> | <a href=\"/\">Top Level</a> ]\n<p/>\n");
		}
		
		File[] listedFiles = (new File(rootDirectory + initialRequest)).listFiles();
		
		Arrays.sort(listedFiles);
		
		if (listedFiles.length > 30) {
			int halfSize = listedFiles.length / 2;
			
			sBuffer.append("<table style=\"border:1px solid #000000;\" cellpadding=\"4\" width=\"100%\">\n");
			sBuffer.append("<tr><td valign=\"top\" width=\"50%\">\n");
			
			sBuffer.append("<table width=\"100%\"><tr><th>Filename:</th><th>Type:</th><th>Size:</th></tr>\n");
			
			for(int i = 0; i < halfSize; i++) {
				String extension = "";
				
				if (listedFiles[i].getName().indexOf(".") != -1) {
					extension = listedFiles[i].getName().substring(listedFiles[i].getName().indexOf(".") + 1);
				}
				
				sBuffer.append("<tr><td><a href=\"");
				sBuffer.append(copiedInitialRequest);
				sBuffer.append(SpaceEncoder.spaceEncode(listedFiles[i].getName()));
				sBuffer.append("\">");
				sBuffer.append(cutString(listedFiles[i].getName(), 40));
				sBuffer.append("</a>\n");
				sBuffer.append("</td><td>\n");
				
				if (listedFiles[i].isDirectory()) {
					sBuffer.append("DIR");
				} else {
					sBuffer.append(MimeTypes.getDefault().get(extension));
				}
				
				sBuffer.append("</td><td>\n");
				sBuffer.append(listedFiles[i].length());
				sBuffer.append("</td></tr>\n");
			}
			
			sBuffer.append("</table></td><td valign=\"top\">\n");
			sBuffer.append("<table width=\"100%\" style=\"border-left:1px solid #000000\">\n");
			sBuffer.append("<tr><th>Filename:</th><th>Type:</th><th>Size:</th></tr>\n");
			
			for(int i = halfSize; i < listedFiles.length; i++) {
				String extension = "";
				
				if (listedFiles[i].getName().indexOf(".") != -1) {
					extension = listedFiles[i].getName().substring(listedFiles[i].getName().indexOf(".") + 1);
				}
				
				sBuffer.append("<tr><td><a href=\"");
				sBuffer.append(copiedInitialRequest);
				sBuffer.append(SpaceEncoder.spaceEncode(listedFiles[i].getName()));
				sBuffer.append("\">");
				sBuffer.append(cutString(listedFiles[i].getName(), 40));
				sBuffer.append("</a>\n");
				sBuffer.append("</td><td>\n");
				
				if (listedFiles[i].isDirectory()) {
					sBuffer.append("DIR");
				} else {
					sBuffer.append(MimeTypes.getDefault().get(extension));
				}
				
				sBuffer.append("</td><td>\n");
				sBuffer.append(listedFiles[i].length());
				sBuffer.append("</td></tr>\n");
			}
			
			sBuffer.append("</td></tr>\n</table>\n");
		} else {
			for(File file : listedFiles) {
				if (file.getName().equals(".") || file.getName().equals("..")) {
					continue;
				}
				
				sBuffer.append("<a href=\"");
				sBuffer.append(copiedInitialRequest);
				sBuffer.append(SpaceEncoder.spaceEncode(file.getName()));
				sBuffer.append("\">");
				sBuffer.append(cutString(file.getName(), 20));
				sBuffer.append("</a>\n");
				sBuffer.append("<br/>\n");
			}
		}
		
		return sBuffer;
	}
}